import numpy as np
import pandas as pd
import matplotlib

matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

y = np.array([1, 3, 3, 4, 5, 6, 4, 8, 9, 10])
x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
plt.scatter(x, y, alpha=0.5)
plt.show()

w = 0
b = 0
rate = 0.01


# 去找线性回归
def gradient_descent(x, y, w, b, rate):
    m = len(x)
    for i in range(m):
        w = w - (1 / m) * rate * ((w * x[i] + b) - y[i]) * x[i]
        b = b - (1 / m) * rate * ((w * x[i] + b) - y[i])
    return w, b


def loss_function(x, y, w, b):
    m = len(x)
    total_error = 0
    for i in range(m):
        total_error += (y[i] - (w * x[i] + b)) ** 2
    return total_error / m

loss = []

for i in range(100):
    w, b = gradient_descent(x, y, w, b, rate)
    if i % 10 == 0:
        t = np.linspace(1, 15, 100)
        plt.plot(t, w * t + b)
        plt.scatter(x, y, alpha=0.5)
        plt.show()
    loss.append(loss_function(x, y, w, b))
    print(w, b)

plt.plot(np.linspace(1, 100, 100), np.array(loss))
plt.show()
